package com.golxen.framework.common.server.game.cmd;


import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.framework.activity.ActivityModule;
import com.golxen.framework.user.player.GamePlayerMgr;
import com.golxen.framework.user.player.GamePlayer;
import com.google.protobuf.Message;
import io.netty.channel.ChannelHandlerContext;

public abstract class AbstractCommand implements Command {

	/**
	 * 返回给客户端的返回值
	 */
	protected int ret = 0;

	public Tuple execute(ChannelHandlerContext ctx, PBPacket packet) throws Exception {
		long userId = packet.getPlayerId();
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);

		Message msg = null;
		Throwable ex = null;
		try {
			msg = parseData(packet);

			beginChange(player);
			if (player != null) {
				player.setLastPingTime(System.currentTimeMillis());
			}
			execute(player, packet);
			sendData(player);

		} catch (Throwable e) {
			ex = e;
			if (player == null) {
				ex = new RuntimeException("GamePlayer is null " + userId + " e: " + e);
			}
		} finally {
			commitChanges(player);

		}
		return new Tuple(ex, msg);
	}

	private void beginChange(GamePlayer player) {
		if (player != null) {
//			player.getModule(ActivityModule.class).beginChanges();
		}
	}

	private void commitChanges(GamePlayer player) {
		if (player != null) {
//			player.getModule(ActivityModule.class).commitChanges();
		}
	}

	public Message parseData(PBPacket packet) throws Exception {
		return null;
	}

	public abstract void execute(GamePlayer player, PBPacket packet) throws Exception;

	public void sendData(GamePlayer player) {
	}
}
